const state = {
	token: uni.getStorageSync('token') || '',
	userInfo: null,
	isLogin: false
}

const mutations = {
	SET_TOKEN(state, token) {
		state.token = token
		uni.setStorageSync('token', token)
	},
	SET_USER_INFO(state, userInfo) {
		state.userInfo = userInfo
		uni.setStorageSync('userInfo', userInfo)
	},
	CLEAR_USER(state) {
		state.token = ''
		state.userInfo = null
		state.isLogin = false
		uni.removeStorageSync('token')
	}
}

const actions = {
	// 登录action 
	login({
		commit
	}, userData) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: '/api/login',
				method: 'POST',
				data: userData,
				success: (res) => {
					commit('SET_TOKEN', res.data.token)
					commit('SET_USER_INFO', res.data.userInfo)
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},

	// 登出action 
	logout({
		commit
	}) {
		commit('CLEAR_USER')
	}
}

const getters = {
	token: state => state.token,
	userInfo: state => {
		if (state.userInfo) {
			return state.userInfo
		} else {
			return uni.getStorageSync('userInfo')
		}
	},
	isLogin: state => state.isLogin
}

export default {
	namespaced: true, // 开启命名空间 
	state,
	mutations,
	actions,
	getters
}